package org.parademo.dao;

import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.parademo.model.UserCommunityEntity;

import java.util.List;

/**
 * The DAO class for user-community interaction.
 */
public class UserCommunityDao extends GenericDao<UserCommunityEntity> {

    public UserCommunityDao(SessionFactory factory) {
        super(factory);
    }

    //TODO: Verify
    public UserCommunityEntity retrieve(java.lang.Long userCommunityId) {

        Query query = getCurrentSession().createQuery(
                "from\n" +
                        "    UserCommunityEntity uc\n" +
                        "where\n" +
                        "    uc.id = :communityId\n"
        );
        query.setLong("communityId", userCommunityId);

        @SuppressWarnings("unchecked")
        List<UserCommunityEntity> userCommunityEntities = query.list();

        if (userCommunityEntities.size() == 0) {
            return null;
        }
        return userCommunityEntities.get(0);
    }

    public void create(UserCommunityEntity entityToCreate) {
        getCurrentSession().save(entityToCreate);
    }

    public void update(UserCommunityEntity entityToUpdate) {
        throw new UnsupportedOperationException("unimplemented"); // todo: implement this
    }

    public void delete(UserCommunityEntity entityToDelete) {
        throw new UnsupportedOperationException("unimplemented"); // todo: implement this
    }


    public List<UserCommunityEntity> getUserCommunities(long userId) {
        Query query = getCurrentSession().createQuery(
                "select\n" +
                        "    uc\n" +
                        "from\n" +
                        "     UserCommunityEntity uc\n" +
                        "        left join fetch uc.community.name\n" +
                        "        left join fetch uc.community.parent\n" +
                        "        left join fetch uc.community.region\n" +
                        "where\n" +
                        "    uc.id = :userId"
        );

        query.setLong("userId", userId);

        @SuppressWarnings("unchecked")
        List<UserCommunityEntity> userCommunities = query.list();

        return userCommunities;
    }
}
